package ws

// ClientManager maintains the set of active Clients and Broadcasts messages to the
// Clients.
type ClientManager struct {
	// Registered Clients.
	Register   chan *Client
	UnRegister chan *Client
	Clients    map[*Client]bool
	Fd         map[string]*Client
}

func NewClientManager() *ClientManager {
	return &ClientManager{
		Register:   make(chan *Client),
		UnRegister: make(chan *Client),
		Clients:    make(map[*Client]bool),
		Fd:         make(map[string]*Client),
	}
}

func (h *ClientManager) Run() {

	for {
		select {
		case client := <-h.Register:
			h.Clients[client] = true
			h.Fd[client.Fd] = client
		case client := <-h.UnRegister:
			if _, ok := h.Clients[client]; ok {
				_ = client.Conn.Close()
				delete(h.Clients, client)
				delete(h.Fd, client.Fd)
			}
		}
	}
}
